<template>
  <div class="content">
    <el-dialog
      :title="dlgCfg.title"
      :visible.sync="dlgCfg.isOpen"
      @close="onCloseDlg"
      :width="dlgCfg.width"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-row type="flex" :gutter="20">
        <!--机构数据-->
        <el-col :span="isRoleUserSelect ? 0 : 5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>机构列表</span>
            </div>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入机构名称" clearable size="small" prefix-icon="el-icon-search" />
              <el-tree :data="deptOptions" :props="deptProps" :expand-on-click-node="false"
                :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" highlight-current node-key="id"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="isRoleUserSelect ? 24 : 18">
          <!-- 查询条件 -->
          <el-form :model="queryParams" ref="userQueryForm" size="small" :inline="true" v-show="true" label-width="68px">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="queryParams.nickName"
                placeholder="请输入用户昵称"
                clearable
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- 查询结果 -->
          <el-table ref="userTable" :key="userData.type" height="500" v-loading="userLoading" :data="userList"
            highlight-current-row @current-change="changeCurrentUser" @selection-change="handleSelectionChange" border>
            <el-table-column v-if="userData.type === 'copy' || userData.type === 'next'" width="55" type="selection" />
            <el-table-column v-else width="30">
              <template slot-scope="scope">
                <el-radio :label="scope.row.userId" v-model="currentUserId">{{ '' }}</el-radio>
              </template>
            </el-table-column>
            <el-table-column label="用户昵称" align="center" prop="nickName" />
            <el-table-column label="在岗状态" align="center" key="workFlag" prop="workFlag" width="100">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.workFlag" size="medium" :type="workFlagType(scope.row.workFlag)">{{ workFlagText(scope.row.workFlag) }}</el-tag>
                <span v-else></span>
              </template>
            </el-table-column>
            <el-table-column label="手机" align="center" prop="phonenumber" />
            <el-table-column label="机构" align="center" prop="dept.deptName" />
          </el-table>
          <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />
        </el-col>
      </el-row>
      <div slot="footer">
        <!-- footer -->
        <el-button @click="dlgCfg.isOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData" :loading="btnSubmiting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { isString } from "@/utils/validate";
import selfForm from "@/mixins/selfForm";
import selfFormRender from "@/mixins/selfFormRender";
import { selectUser, deptTreeSelect } from '@/api/system/user'
import { batchTransfer } from '@/api/workflow/task'

export default {
  name: "CptTaskTransferDlg",
  mixins: [selfForm, selfFormRender],
  props: {},
  data() {
    return {
      dlgCfg: {
        isOpen: false,
        title: "转办任务",
        width: "80%",
        btnLoading: false,
      },
      taskForm: {
        taskId: "",
        userId: "",
        comment: "",
        procInsId: "",
      },
      isRoleUserSelect: true,
      // 机构名称
      deptName: undefined,
      // 机构树选项
      deptOptions: undefined,
      deptProps: {
        children: "children",
        label: "label"
      },
      userLoading: false,
      userData: {
        title: '',
        type: 'transfer',
        open: false,
      },
      // 用户表格数据
      userList: null,
      currentUserId: null,
      userMultipleSelection: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        deptId: undefined
      },
      btnSubmiting: false,
      total: 0,
      todoTasks: []
    };
  },
  computed: {
    workFlagText() {
      return val => {
        switch (val) {
          case '1': return '离岗'
          case '0': return '在岗'
        }
      }
    },
    workFlagType() {
      return val => {
        switch (val) {
          case '1': return 'warning'
          case '0': return 'success'
        }
      }
    },
  },
  mounted() {},
  methods: {
    showDlg(tasks) {
      this.initMyFormData(tasks);
    },
    onDlgOK() {
      this.$emit("submit");
    },
    onDlgCancel() {
      this.$emit("cancel");
    },
    onCloseDlg() {
      this.currentUserId = null
      this.userMultipleSelection = []
      this.$emit("close");
    },
    initMyFormData(tasks) {
      if (tasks && tasks.length) {
        this.todoTasks = tasks
        this.dlgCfg.isOpen = true;
        this.getTreeSelect();
        this.getList()
      }
    },
    /** 查询机构下拉树结构 */
    getTreeSelect() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /** 查询用户列表 */
    getList() {
      this.userLoading = true;
      if(this.isRoleUserSelect) {
        /** 查询上级角色下用户列表 */
        // selectRoleUser({
        //   ...this.queryParams,
        //   'type': '0',
        //   'strRoleIds': this.$store.state.user.userInfo.roles.map(item => { return item.roleId }),
        //   'deptId': ''
        // }).then(response => {
        //   this.userList = response.rows;
        //   this.total = response.total;
        //   this.toggleSelection(this.userMultipleSelection);
        //   this.userLoading = false;
        // });
        
        // 选择机构下的人员 
        this.queryParams.deptId = this.$store.state.user.userInfo.deptId
        selectUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.toggleSelection(this.userMultipleSelection);
          this.userLoading = false;
        });
      } else {
        selectUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.toggleSelection(this.userMultipleSelection);
          this.userLoading = false;
        });
      }
    },
    changeCurrentUser(val) {
      this.currentUserId = val ? val.userId : null
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.userMultipleSelection = selection
    },
    toggleSelection(selection) {
      if (selection && selection.length > 0) {
        this.$nextTick(() => {
          selection.forEach(item => {
            let row = this.userList.find(k => k.userId === item.userId);
            this.$refs.userTable.toggleRowSelection(row);
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    setTaskFormCommentDefault() {
      if (this.taskForm && (this.taskForm.comment === null || this.taskForm.comment === undefined || this.taskForm.comment === '')) {
        this.taskForm.comment = '   '
      }
    },
    submitUserData() {
      let type = this.userData.type;
      if (type === 'copy' || type === 'next') {
        if (!this.userMultipleSelection || this.userMultipleSelection.length <= 0) {
          this.$modal.msgError("请选择用户");
          return false;
        }

        // 指定审批人目前临时处理为支持单人 by gaogm
        if (type === 'next' && this.userMultipleSelection.length > 1) {
          this.$modal.msgError("请选择一个用户");
          return false;
        }

        let userIds = this.userMultipleSelection.map(k => k.userId);
        if (type === 'copy') {
          // 设置抄送人ID信息
          this.copyUser = this.userMultipleSelection;
          this.taskForm.copyUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        } else if (type === 'next') {
          // 设置下一级审批人ID信息
          this.nextUser = this.userMultipleSelection;
          this.taskForm.nextUserIds = userIds instanceof Array ? userIds.join(',') : userIds;
        }
        this.userData.open = false;
      } else {
        this.setTaskFormCommentDefault()
        if (!this.taskForm.comment) {
          this.$modal.msgError("请输入审批意见");
          return false;
        }
        if (!this.currentUserId) {
          this.$modal.msgError("请选择用户");
          return false;
        }
        if(this.userList) {
          let curUser = this.userList.find(v => { return  v.userId === this.currentUserId})
          if (curUser && curUser.workFlag === '1') {
            this.$modal.msgError("该人员不在岗，不能指派");
            return
          }
        }
        this.taskForm.userId = this.currentUserId;
        if (type === 'delegate') {
          const taskFormRef = this.$refs.taskFormParser;
          const isExistTaskForm = taskFormRef !== undefined;
          if (isExistTaskForm) {
            this.taskForm.variables = taskFormRef[taskFormRef.formConfCopy.formModel]
          }
          delegate(this.taskForm).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.goBack();
          });
        }
        if (type === 'transfer') {
          this.btnSubmiting = true
          let params = this.todoTasks.map(t => {
            const p = {
              ...this.taskForm
            }
            p.procInsId = t.procInsId
            p.taskId = t.taskId
            return p
          })
          batchTransfer(params).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.btnSubmiting = false
            this.dlgCfg.isOpen = false
            this.onDlgOK()
          }); 
        }
      }
    },
    handleUserQuery() {
      this.getList();
    },
    resetUserQuery() {
      if (this.$refs.tree) {
        this.$refs.tree.setCurrentKey(null);
      }
      this.resetForm("userQueryForm");
      this.queryParams.deptId = undefined;
      this.queryParams.nickName = undefined;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
}
</style>
